package com.xiaofeng.club.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.nacos.api.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaofeng.club.gateway.entity.AuthPermission;
import com.xiaofeng.club.gateway.entity.AuthRole;
import com.xiaofeng.club.gateway.redis.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: chc
 * @Date: 2024/02/07/15:23
 * @Description:
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authRolePrefix);
    }

    //公共抽取方法
    public List<String> getAuth(String loginId,String prefix){
        //构建缓存key
        String authKey = redisUtil.buildKey(prefix, loginId.toString());
        //通过关键字key在缓存中命中数据
        String authValue = redisUtil.get(authKey);
        //判断是否命中缓存
        if (StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList = new LinkedList<>();
        //判断是否是角色缓存
        if (authRolePrefix.equals(prefix)){
            //将redis中的数据反序列化
            List<AuthRole> roleList = new Gson().fromJson(authValue,new TypeToken<List<AuthRole>>(){
            }.getType());
            //根据角色关键字遍历循环获取value
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }else if (authRolePrefix.equals(prefix)){//判断是否是权限缓存
            //将redis中的数据反序列化
            List<AuthPermission> permissionList = new Gson().fromJson(authValue,new TypeToken<List<AuthPermission>>(){
            }.getType());
            //根据权限关键字遍历循环获取value
            authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }
}

